package com.lzx.iteam.net;

import android.os.Message;
import com.lzx.iteam.bean.CRMBaseBean;
import com.lzx.iteam.bean.CRMChanceBean;
import com.lzx.iteam.bean.CRMCommentData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static com.lzx.iteam.DialerApp.map;

public class CRMChanceUpdateMsg extends CcMsgStructure {

    private Message mCallBack;

    public CRMChanceUpdateMsg( Message callback) {
        this.mCallBack = callback;
    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<CRMCommentData> chances = new ArrayList<CRMCommentData>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            if (jsonObject.has("history")) {
                JSONArray history = jsonObject.getJSONArray("history");
                for (int i = 0; i < history.length(); i++) {
                    JSONObject item = history.getJSONObject(i);
                    CRMCommentData commentData = new CRMCommentData();
                    commentData.setContent(item.getString("content"));
                    commentData.setType(item.getInt("type"));
                    commentData.setcTime(item.getString("ctime"));
                    commentData.setUserId(item.getString("uid"));
                    commentData.setUserName(item.getString("uname"));
                    commentData.setUserImage(item.getString("image"));
                    commentData.setFlag(item.getInt("flag"));
                    if (item.has("attachment")){
                        commentData.setAttachments(item.getJSONArray("attachment").toString());
                    }
                    chances.add(commentData);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (mCallBack != null) {
            mCallBack.arg1 = 0;
            Collections.reverse(chances);
            mCallBack.obj = chances;
            mCallBack.sendToTarget();
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mCallBack != null) {
            mCallBack.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mCallBack.obj = errorMsg;
            } else {
                mCallBack.obj = Constants.NETWORK_WRROR;
            }
            mCallBack.sendToTarget();
        }
    }
}
